const app = getApp()
const promisify = require('../../utils/promisify')

Page({
  data: {
    parents: [],
    total: 0,
    selectAll: false,
    pendding: [
      []
    ],
    telephone: "",
    addr: ""
  },

  onLoad: function (data) {
    /**
     * 初始化时，从globalData获取购物车信息，存在parents中
     */
    let that = this
    let parents = []
    app.globalData.globalCart.forEach((item, index) => {
      if (item.items.length != []) {
        item.items.forEach((data, i) => {
          if (data.num === 1) {
            data.subStyle = "cannotsub"
          }
        })
        parents.push(item)
      }
    })
    that.setData({
      parents: parents
    })
    that.totalChange() //计算总价
    parents.forEach((item, index) => {
      //判断parent是否选中
      that.isParentSelected(index)
    })
    that.isAllSelected()
    console.log(parents)
  },

  toBuy: function () {
    let that = this
    let items = JSON.stringify(that.data.parents)
    promisify(wx.navigateTo)({
      url: `../buy/buy?items=` + items
    })
  },

  itemChange: function (item, index1, index2, delay) {
    let that = this
    if (!that.data.pendding[index1][index2]) {
      that.data.pendding[index1][index2] = app.throttle(app.postItemChange, delay)
    }
    that.data.pendding[index1][index2](item)
  },

  change: function (e) {
    /**
     * 改变物品数量的函数
     * 根据id和parentId，改变对应item的数量
     * 最低减到1
     */
    let that = this
    let parents = that.data.parents
    let id = Number(e.target.dataset.id)
    let parentId = Number(e.target.dataset.parentid)
    let method = e.target.dataset.method
    let ids = that.findItem(id, parentId)
    let itemIndex = ids.itemIndex
    let parentIndex = ids.parentIndex
    let item = parents[parentIndex].items[itemIndex]
    if (method === "add") {
      if (item.num === 1) {
        item.subStyle = "cansub"
      }
      item.num++
    } else if (method === "sub") {
      if (item.num > 2) {
        item.num--
      } else if (item.num === 2) {
        item.num--
        item.subStyle = "cannotsub"
      }
    }
    that.setData({
      parents
    })
    that.itemChange(item, parentIndex, itemIndex, 2000)
    that.upDateLocalStorage()
    that.totalChange()
  },

  itemSelect: function (e) {
    /**
     * 点击物品的选中框
     * 将物品的select属性取反
     * 改变总价
     * 判断父类是否全选
     * 判断全部是否全选
     */
    let that = this
    let id = e.target.dataset.id
    let parentId = Number(e.target.dataset.parentid)

    console.log(id, parentId)
    let ids = that.findItem(id, parentId)
    let parentIndex = ids.parentIndex
    let itemIndex = ids.itemIndex
    let select = !that.data.parents[parentIndex].items[itemIndex].select
    let findSelect = "parents[" + parentIndex + "].items[" + itemIndex + "].select"
    that.setData({
      [findSelect]: select
    })
    that.totalChange()
    that.isParentSelected(parentIndex)
    that.isAllSelected()
    that.upDateLocalStorage()
  },

  parentSelect: function (e) {
    /**
     * 选中parent的函数
     * 若没有被选中，则选中，并且将每一个子元素选中
     * 如果选中，则取消每一个子元素的选中
     * 改变总价
     * 检测是否全选
     */
    let that = this
    let parentId = e.target.dataset.parentid
    let parentIndex = that.findParent(parentId)
    let parent = that.data.parents[parentIndex]
    let findParent = "parents[" + parentIndex + "]"

    if (parent.select === false) {
      change(true)
    } else {
      change(false)
    }
    that.isAllSelected()
    that.totalChange()
    that.upDateLocalStorage()

    function change(data) {
      parent.select = data
      parent.items.forEach((item, index) => {
        item.select = data
      })
      that.setData({
        [findParent]: parent
      })
    }
  },

  allSelect: function () {
    /**
     * 全选的函数
     * 若果没有被选中，则选中每一个子元素
     * 如果选中，则取消每一个元素的选择
     */
    let that = this
    let parents = that.data.parents

    if (that.data.allSelect === true) {
      change(false)
    } else {
      change(true)
    }
    that.totalChange()
    that.upDateLocalStorage()

    function change(data) {
      parents.forEach((item, index) => {
        item.select = data
        item.items.forEach((d, i) => {
          d.select = data
        })
      })
      that.setData({
        allSelect: data,
        parents: parents
      })
    }
  },

  isParentSelected: function (parentIndex) {
    /**
     * 判断parent是否满足全选的条件
     * 如果所有item都被选中，那么该parent满足选中条件
     */
    let that = this
    let parent = that.data.parents[parentIndex]
    let flag = true
    let findParentSelect = "parents[" + parentIndex + "].select"
    parent.items.forEach((item, index) => {
      if (!item.select) {
        flag = false
      }
    })
    if (flag) {
      that.setData({
        [findParentSelect]: true
      })
    } else {
      that.setData({
        [findParentSelect]: false
      })
    }
  },

  isAllSelected: function () {
    /**
     * 判断是否全选
     * 如果所有parent都被选中，则满足全选条件
     * 如果parent为空，则也不满足条件
     */
    let that = this
    let parents = that.data.parents
    let flag = true
    if (parents.length === 0) {
      flag = false
    }
    parents.forEach((item, index) => {
      if (!item.select) {
        flag = false
      }
    })
    if (flag) {
      that.setData({
        allSelect: true
      })
    } else {
      that.setData({
        allSelect: false
      })
    }
  },

  findItem: function (id, parentId) {
    /**
     * 根据id和parentId返回该物品的index和parentIndex
     */
    let that = this
    let parentIndex = that.findParent(parentId)
    let itemIndex
    that.data.parents[parentIndex].items.forEach((item, index) => {
      if (item.id === id) {
        itemIndex = index
      }
    })
    return {
      itemIndex,
      parentIndex
    }

  },

  findParent: function (parentId) {
    /**
     * 根据parentId返回parentIndex
     */
    let that = this
    let parentIndex
    that.data.parents.forEach((item, index) => {
      if (item.parentId === parentId) {
        parentIndex = index
      }
    })
    return parentIndex
  },

  totalChange: function () {
    /**
     * 计算总价的函数
     * 判断物体select是否为true
     * 如果被选中，则计算该物品的价格
     */
    let that = this
    let total = 0
    let parents = that.data.parents
    parents.forEach((item, index) => {
      let items = item.items
      items.forEach((data, i) => {
        if (data.select) {
          total += data.price * data.num
        }
      })
    })
    that.setData({
      total
    })
  },

  deleteItemListener: function (e) {
    let that = this
    let id = Number(e.target.dataset.id)
    let parentId = Number(e.target.dataset.parentid)
    that.deleteItem(id, parentId)
  },

  deleteItem: function (id, parentId) {
    /**
     * 删除商品的函数
     * 从相应的parent中删除item
     * 如果删除之后parent为空，则删除parent
     * 如果删除之后parent不为空，则判断parent和all是否选中
     * 计算总价
     */
    let that = this
    let ids = that.findItem(id, parentId)
    let itemIndex = ids.itemIndex
    let parentIndex = ids.parentIndex
    let parents = that.data.parents

    // 深拷贝，不然item会被删除
    let item = JSON.parse(JSON.stringify(that.data.parents[parentIndex].items[itemIndex]))
    item.num = 0
    that.itemChange(item, parentIndex, itemIndex, 0)

    parents[parentIndex].items.splice(itemIndex, 1)

    if (parents[parentIndex].items.length != 0) {
      // 删除后parent不为空
      that.setData({
        parents
      })
      that.isParentSelected(parentIndex)
    } else {
      // 删除后parent为空
      parents.splice(parentIndex, 1)
      that.setData({
        parents
      })
    }
    that.isAllSelected()
    that.totalChange()
    that.upDateLocalStorage()
  },

  deleteParentListener: function (e) {
    let that = this
    let parentId = e.target.dataset.parentid
    that.deleteParent(parentId)
  },

  deleteParent: function (parentId) {
    /**
     * 删除parent的函数
     * 从parents中删除数据
     * 判断all是否选中
     * 计算总价
     */
    let that = this
    let parentIndex = that.findParent(parentId)
    let parents = that.data.parents

    let parent = JSON.parse(JSON.stringify(parents[parentIndex]))
    parent.items.forEach((item, index) => {
      item.num = 0
      that.itemChange(item, parentIndex, index, 0)
    })

    parents.splice(parentIndex, 1)
    that.setData({
      parents
    })
    that.isAllSelected()
    that.totalChange()
    that.upDateLocalStorage()
  },

  upDateLocalStorage: function (parent) {
    /**
     * 更新本地缓存的函数
     * 使用深拷贝，拷贝parents，避免与调用函数中的parents冲突
     */
    let that = this
    let parents = JSON.parse(JSON.stringify(that.data.parents))
    let globalCart = app.globalData.globalCart

    parents.forEach((item, index) => {
      /**
       * 在购物车界面，最低减到1，subStyle为cannotsub
       * 但是商品列表页，商品数量为1时，应该为cansub，这里统一一下
       */
      item.items.forEach((data, i) => {
        if (data.num === 1) {
          data.subStyle = "cansub"
        }
      })
    })

    globalCart.forEach((item, index) => {
      let flag = false
      parents.forEach((data, i) => {
        if (item.parentId === data.parentId) {
          flag = true
          globalCart[index] = data
        }
      })
      if (!flag) {
        /**
         * 删除parent之后，parents中就会少一个元素
         * 上面的循环就不会改变删除后的parent的本地缓存 
         **/
        item.select = false
        item.items = []
      }
    })
    app.globalData.globalCart = globalCart
    promisify(wx.setStorage)({
      key: "globalCart",
      data: globalCart
    })
  },

  buy: function () {
    /**
     * 购买功能
     * 如果没有选中商品，提醒用户
     * 确认后，将购物车中所有选中的物品发送给后端
     * 并且删除相应购物车中的物品
     */
    let that = this
    let parents = that.data.parents
    let selectedItem = []
    //  获取所有被选中的物品
    parents.forEach((item1, index1) => {
      item1.items.forEach((item2, index2) => {
        if (item2.select === true) {
          let obj = {
            id: item2.id,
            parentId: item2.parentId,
            num: item2.num,
            price: item2.price,
            name: item2.name,
            brief: item2.brief,
            img: item2.img
          }
          selectedItem.push(obj)
        }
      })
    })

    if (selectedItem.length === 0) {
      // 没有商品被选中
      wx.showToast({
        title: '请先选中商品',
        icon: 'none',
        duration: 2000
      })
    } else {
      promisify(wx.showModal)({
        title: "确认购买",
        confirmText: "确定",
        cancelText: "取消"
      }).then(
        data => {
          if (data.confirm) {
            /**
             * 确认后，暂时将订单存到localStorage
             * 并删除购物车中相应数据
             */
            app.globalData.globalOrders.push(selectedItem)
            promisify(wx.setStorage)({
              key: "globalOrders",
              data: app.globalData.globalOrders
            })
            selectedItem.forEach((item, index) => {
              let id = item.id
              let parentId = item.parentId
              that.deleteItem(id, parentId)
            })
            wx.showToast({
              title: "购买成功",
              icon: "success",
              duration: 2000
            })
          }
        },
        err => {
          console.log(err)
        }
      )
    }
  },

  // confirm: function () {
  //   let that = this
  //   if (that.checkPhone() && that.checkAddr()) {

  //   }
  // },
  bindInput: function (e) {
    /**
     * 为输入框绑定数据
     */
    let data = e.target.dataset.data
    this.setData({
      [data]: e.detail.value
    })
  },
  checkPhone: function () {
    var reg = /^((1[3-9][0-9])+\d{8})$/;
    if (!reg.test(this.data.telephone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },
  checkAddr: function () {
    if (!this.data.addr) {
      wx.showToast({
        title: '请输入收货地址',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    return true
  },
  confirm: function () {
    /**
     * 购买功能
     * 如果没有选中商品，提醒用户
     * 确认后，将购物车中所有选中的物品发送给后端
     * 并且删除相应购物车中的物品
     */
    let that = this
    let parents = that.data.parents
    let selectedItem = []
    //  获取所有被选中的物品
    parents.forEach((item1, index1) => {
      item1.items.forEach((item2, index2) => {
        if (item2.select === true) {
          let obj = {
            id: item2.id,
            quantity: item2.num,
            parentId: Number(item2.parentId)
          }
          selectedItem.push(obj)
        }
      })
    })

    selectedItem = JSON.parse(JSON.stringify(selectedItem))
    if (selectedItem.length === 0) {
      // 没有商品被选中
      wx.showToast({
        title: '请先选中商品',
        icon: 'none',
        duration: 2000
      })
    } else if (that.checkPhone() && that.checkAddr()) {
      promisify(wx.showModal)({
        title: "确认购买",
        confirmText: "确定",
        cancelText: "取消"
      }).then(
        data => {
          if (data.confirm) {
            /**
             * 确认后，暂时将订单存到localStorage
             * 并删除购物车中相应数据
             */

            let items = "["
            selectedItem.forEach((item, index) => {
              items += "{Id:" + item.id + ",quantity:" + item.quantity + "},"
            })
            items = items.slice(0, items.length - 1) + "]"

            promisify(wx.request)({
              url: `https://www.cumthing.world/cumthing/product/order/create`,
              method: "POST",
              header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': app.globalData.token
              },
              data: {
                name: app.globalData.userName,
                phone: that.data.telephone,
                address: that.data.addr,
                userId: app.globalData.userId,
                items: items
              }
            }).then(
              data => {
                if (data.data.code === 0) {
                  app.globalData.globalOrders.push(selectedItem)
                  promisify(wx.setStorage)({
                    key: "globalOrders",
                    data: app.globalData.globalOrders
                  })
                  selectedItem.forEach((item, index) => {
                    let id = item.id
                    let parentId = item.parentId
                    that.deleteItem(id, parentId)
                  })
                  wx.showToast({
                    title: "购买成功",
                    icon: "success",
                    duration: 2000
                  })
                }
              },
              err => {
                console.log(err)
              }
            )
          }
        },
        err => {
          console.log(err)
        }
      )
    }
  }
})
